import os
import subprocess
import shlex
import logging 
LOGGER = logging.getLogger("PackageManager")
LOGGER.setLevel(logging.INFO)
logging.fatal

def download_and_extract(url, output_dir):
    filename = os.path.basename(url)
    if os.path.isdir(output_dir) and not os.path.exists(output_dir):
        os.makedirs(output_dir)
    elif os.path.isfile(output_dir):
        output_dir = os.path.dirname(output_dir)
        filename = os.path.basename(output_dir)
        os.makedirs(output_dir, exist_ok=True)
    else:
        ValueError("Not find output dir {}".format(output_dir))

    output_filename = os.path.join(output_dir,filename)    
    if not os.path.exists(output_filename):
        command = "wget {} -O {}".format(url,output_filename)
        args = shlex.split(command)
        p = subprocess.Popen(args,stdout=subprocess.PIPE)
"""
>>> filename_and_ext("temp.zip")
("temp","zip")
>>> filename_and_ext("temp.tar.gz")
("temp","zip.gz")
"""
def filename_and_ext(filename):
    elements = os.path.basename(filename).split(".")
    if len(elements)==1:
        return filename,None
    elif len(elements) == 2:
        return elements[0],elements[1]
    else:
        return elements[0],".".join(elements[1:])
        
def unzip_file(filename,output):
    if not os.path.exists(filename):
        ValueError("{} not exist!".format(filename))
    name,ext = os.path.splitext(os.path.basename(filename))
    command = None
    if ext == 'zip':
        command = shlex.split("zip {} -d {}".format(filename,output))
    elif ext == 'tar.gz':
        command = shlex.split("tar xzvf {} -C {}".format(filename,output))
    elif ext == 'tar.xz':
        command = shlex.split("tar xJvf {} -C {}".format(filename,output))
    else:
        ValueError("Current {} not be supported".format(ext))
    LOGGER.info("Command is = {}".format(command))
    if command is not None:
        subprocess.Popen(command,stdout=subprocess.PIPE)

FFMPEG_URL="https://github.com/FFmpeg/FFmpeg/archive/refs/tags/n4.1.8.zip"
download_and_extract(FFMPEG_URL,'/tmp/')
unzip_file('/tmp/n4.1.8.zip','/tmp')
